package gspushmq.v1.produce.job.wb;

import java.net.InetSocketAddress;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.UUID;

import org.java_websocket.WebSocket;
import org.quartz.DisallowConcurrentExecution;

import ggframework.mongodb.BasicDBObject;
import ggframework.mongodb.DBCollection;
import ggframework.mongodb.DBObject;
import ggframework.util.GGConfigurer;
import gspushmq.model.Message;
import gspushmq.model.User;
import gspushmq.util.MongoUtil;
import gspushmq.v1.produce.job.core.GGServiceJob;
import gspushmq.v1.subscribe.GGSubscribe;
import gspushmq.v1.websocket.core.GGPusherEnum;
import gspushmq.v1.websocket.core.GGWebSocket;

/**
 *
 * 
 * @version 1.0
 * @since JDK1.7
 * @author yutao
 * @company 上海朝阳永续信息技术有限公司
 * @copyright (c) 2016 SunTime Co'Ltd Inc.All rights reserved.
 * @date 2019年1月11日上午10:40:44
 */
@DisallowConcurrentExecution
public class GGWbJob extends GGServiceJob {

	@Override
	public void doServiceJob(Map<String, Object> args) {
		
		String env = GGConfigurer.get("ggpush.env", "pro");
		
		GGWebSocket webSocket = GGPusherEnum.pusher.getPusher();
		int connectionSize = 0;
		Collection<WebSocket> connections = webSocket.getConnections();
		if (connections != null) {
			connectionSize = connections.size();
		}
		
		int port = webSocket.getPort();
		
		InetSocketAddress address = webSocket.getAddress();
		
		String uuid = UUID.randomUUID().toString().replaceAll("-", "");
		
		DBCollection webscketColl = MongoUtil.getFtAccountBehaviorCollection("cbs_websocket_record");
		BasicDBObject insert = new BasicDBObject();
		insert.append("connections", connectionSize);
		insert.append("port", port).append("uuid", uuid);
		insert.append("address", address.toString()).append("env", env);
		insert.append("type", 1).append("insert_time", new Date());
		webscketColl.insert(insert);
		List<DBObject> wstList = new ArrayList<>();
		for (WebSocket wst : connections) {
			User user = GGSubscribe.wstUser.get(wst);

			BasicDBObject wb = new BasicDBObject();
			if (user != null) {
				String productLine = user.getProductLine();
				String accountId = user.getAccountId();
				wb.append("product_line", productLine).append("account_id", accountId);
			}
			wb.append("uuid", uuid)
			.append("isOpen", wst.isOpen()).append("getReadyState", wst.getReadyState().toString())
			.append("env", env).append("type", 2).append("insert_time", new Date());
			wb.append("wst_class", wst.toString());
			Message message = GGSubscribe.wstMessage.get(wst);
			if (message != null) {
				wb.append("version", message.getVersion());
			}
			wstList.add(wb);
		}
		webscketColl.insert(wstList);
		wstList = null;
		insert = null;
	}

	@Override
	protected String setJobName() {
		return "webscoket写入数据库";
	}
}
